/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dac.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp_max31856.h"
#include "stdint.h"
#include "bsp_pid.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t uch_reg[8];
uint8_t uch_cjth,uch_cjtl,uch_ltcbh,uch_ltcbm,uch_ltcbl,uch_sr;
uint32_t temperature_value;
char s[64];
float  f_cold_junction_temperature, f_linearized_tc_temperature;
float f_expect_temperature = 0.f;
float DAC_OUT = 0;
float DAC_OUT_u = 0;
extern uint8_t uch_cr0,uch_cr1,uch_mask;
int fputc(int ch, FILE *f)
{
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
  return ch;
}

/**
 * @brief ��ʾ��������ע�⾫�ȷ�Χ����Ҫ����Ļ��������Ӧ������ACC�����Ϊ�˸����������
 * @param name �ؼ����ƣ��鿴�����ñ�display_conf��
 * @param data
 */
#define ACC 1000 // С������ʾ����
void HIM_send_float(char *name, float data)
{
	printf("%s.val=%d\xff\xff\xff", name, (int)(data * ACC));
}
#define x1 "n0"

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI1_Init();
  MX_DAC1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  MAX31856_Init();         //初始化MAX31856
  pit_init();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		HAL_Delay(200);                             //设置两次转换之间的启动延迟，可根据要求进行调�??
    MAX31856_Start_Conversion(One_Shot_Conversion);  //使能单次转换

    HAL_Delay(169);
    MAX31856_Read_Nregisters(0x0A, uch_reg,6);  //�??0x0A地址�??始，读取6个字节数�??
    
    uch_cjth=uch_reg[0];uch_cjtl=uch_reg[1];                //将读取到的结果赋值给对应的寄存器变量
    uch_ltcbh=uch_reg[2];uch_ltcbm=uch_reg[3];uch_ltcbl=uch_reg[4];
    uch_sr=uch_reg[5];
    
    if(uch_sr==NO_Fault)                        //如果没有�??测到故障
    {
      //计算冷端温度测量结果
      temperature_value=(uch_cjth<<8|uch_cjtl)>>2;      //构�?�冷端温度数�??      
      if((uch_cjth&0x80)==0x80)                           //如果CJTH的最高位�??1，则为负温度�??
			{
				temperature_value=0x3FFF-temperature_value+1;
				f_cold_junction_temperature=0-temperature_value*Cold_Junction_Resolution;   //计算得到冷端温度值（负�?�）
			}        
      else
        f_cold_junction_temperature=temperature_value*Cold_Junction_Resolution;     //计算得到冷端温度值（正�?�）
//        //串口输出冷端测量结果
//        printf("f_cold_junction_temperature=%8.4f\n",f_cold_junction_temperature);    
//        //计算热电偶测温结�??
        temperature_value=(uch_ltcbh<<16|uch_ltcbm<<8|uch_ltcbl)>>5;         //构�?�热电偶温度数据
      if((uch_ltcbh&0x80)==0x80)                                          //如果LTCBH�??高位�??1，则为负温度�??
			{
				temperature_value=0x7FFFF-temperature_value+1;
				f_linearized_tc_temperature=0-temperature_value*TC_Resolution;  //计算得到热电偶转换温度�??(负�??)
			}
      else
			  f_linearized_tc_temperature=temperature_value*TC_Resolution;     //计算得到热电偶转换温度�??(正�??)
				//串口输出热电偶转换温度结�??
//			  printf("f_linearized_tc_temperature=%8.4f\n",f_linearized_tc_temperature);
//			  printf("\n");
			DAC_OUT = pid_calc(&pid_temp_struct,f_expect_temperature,f_linearized_tc_temperature);
			DAC_OUT_u = -DAC_OUT /3.3f*4095.f;
			HAL_DAC_SetValue(&hdac1,DAC_CHANNEL_1,DAC_ALIGN_12B_R,(uint32_t)DAC_OUT_u);
			HAL_DAC_Start(&hdac1,DAC_CHANNEL_1);
      
    }    
    else                                //如果�??测到故障，则�??要进行故障处�??   
    {
      if((uch_sr&CJ_Range_Fault)==CJ_Range_Fault)                      
         printf("Cold Junction Out-of-Range\n");
      if((uch_sr&TC_Range_Fault)==TC_Range_Fault)
         printf("Thermocouple Out-of-Range\n");
      if((uch_sr&CJHIGH_Fault)==CJHIGH_Fault)
         printf("Cold Junction High Fault\n");
      if((uch_sr&CJLOW_Fault)==CJLOW_Fault)
         printf("Cold Junction Low Fault\n");
      if((uch_sr&TCHIGH_Fault)==TCHIGH_Fault)
         printf("Thermocouple Temperature High Fault\n");
      if((uch_sr&TCLOW_Fault)==TCLOW_Fault)
         printf("Thermocouple Temperature Low Fault\n");
      if((uch_sr&OVUV_Fault)==OVUV_Fault)
         printf("Overvoltage or Undervoltage Input Fault\n");
      if((uch_sr&OPEN_Fault)==OPEN_Fault)
         printf("Thermocouple Open-Circuit Fault\n");
      
		  //如果Fault Mode = 中断模式
			MAX31856_Write_Register(0x82, 0xFF);        //屏蔽/FAULT输出
			MAX31856_Clear_Fault_Status();                    //清除故障状�??
			MAX31856_Write_Register(0x82, 0x00);        //重新解除3屏蔽
    }
		
		HIM_send_float(x1,f_linearized_tc_temperature);

		
		
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 42;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
